package com.rbs.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //将流中的内容加载到properties集合
    private static Properties p = new Properties();
    //创建线程绑定对象 指定泛型Connection
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();
    //保证类加载时只读取一次配置文件
    static {
        InputStream is = null;
        try {
            //将配置文件中的内容读取到流中
            is = new FileInputStream("E:\\IdeaProjects\\maven_day01\\src\\main\\resources\\jdbc.properties");
            p.load(is);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (is != null){
                try {
                    is.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
    //获取连接的方法
    public static Connection getConn(){
        Connection conn = tl.get();
        if (conn == null){
            try {
                //加载驱动
                Class.forName(p.getProperty("Driver"));
                //获取连接
                String url = p.getProperty("url");
                String username = p.getProperty("username");
                String password = p.getProperty("password");
                conn = DriverManager.getConnection(url,username,password);
                tl.set(conn);
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        return conn;
    }
    //释放资源的方法
    public static void close(Connection conn, PreparedStatement psmt, ResultSet rs){
        try {
            if(conn!=null) conn.close();
            if(psmt!=null) psmt.close();
            if(rs!=null) rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
